<template>
  <div class="layout-container">
    <div class="layout-container-table">
      <Table ref="table" v-model:page="page" v-loading="loading" :showSelection="false"
       :data="tableData"
        @getTableData="getTableData" @selection-change="handleSelectionChange">
            <el-table-column 
            v-for="(item,index) in columns" :type="item.type" :key="index"
            :label="item.label"
            :width="item.width"
            :property="item.property">
                <template  #default="scope" >
                        <span :class="[item.classes]">{{scope.row[item.property]}}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="220">
                <template #default="scope">
                    <el-button type="" @click="goApp(scope.row,scope)">查看</el-button>
                    <el-button type="success" @click="handleAdd(scope.row,scope)">修改</el-button>
                </template>
            </el-table-column>
      </Table>
    </div>
  </div>
</template>
<script setup lang="ts">
import {  ref, reactive ,onActivated, nextTick} from "vue";
import { Page } from "@/components/table/type";
import { ElMessage, ElMessageBox ,ElIcon } from "element-plus";
import BatchImportDialog from "@/components/uploadFile/batchImportDialog.vue";
import Table from "@/components/table/index.vue";
import {
  productList,productUpdate,productPicture,productImports
} from "@/api/exchange.ts";
import {
  notifyList,notifyColumnList,deleteNotify,modifyNotify
} from "@/api/notice.ts";


import { dateFormat, intervalTime, calculateDiffTime } from "@/utils/index.ts";
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";
import { ossPrefixNew } from "@/utils/index.ts";
const router = useRouter();
const store = useStore();
const adminInfo = reactive(store.state.user.adminInfo);

// 存储搜索用的数据
const query = reactive({
  "column_id":"",
  "title":"",
});
const columnOptions = ref([])
const getNotifyColumnList = ()=>{
  notifyColumnList().then(res => {
    if(res.code == 200){
      res.data.map(item => {
        item.label = item.name
        item.value = item.Id
      })
      columnOptions.value = res.data;
    }
    
  })
}



// 分页参数, 供table使用
const page: Page = reactive({
  index: 1,
  size: 50,
  total: 0,
});
// 重置
const resetSearch = () => {
    query.column_id = ''//
    query.title = ''//, // string
    getTableData(true);
}
const columns = ref([])
const columns1 = reactive([
   {
        label:'标题',
        property:'title',
    
    },
]);
columns.value = columns1
const loading = ref(false);
const tableData = ref([]);

const getParams = ()=>{
    return {}
}

const table = ref()
const checkAll = ref(false)
const changeAll = (e:any)=>{
    console.log(checkAll.value)
    if(e){
      if(selectData.value.length == tableData.value.length) return
        table.value.$refs.systemTable.toggleAllSelection()
    }else{
      selectData.value = [];
      table.value.$refs.systemTable.clearSelection()
    }
}
// 勾选数据
const selectData = ref([]); // 系统id
const handleSelectionChange = (data: any) => {
  selectData.value = [];
  if(data.length){
    if(data.length != tableData.value.length){
      checkAll.value = false
    }
    data.forEach((item: any) => {
      selectData.value.push(item.Id);
    });
  }
};

// 获取表格数据
// params <init> Boolean ，默认为false，用于判断是否需要初始化分页
const getTableData = (init: Boolean) => {
 tableData.value = [
    {
        title:'用户协议',
        id:'ZXZ_USER_AGREEMENT'
    },{
        title:'隐私协议',
        id:'ZXZ_PRIVACY_AGREEMENT'
    },{
        title:'有效人数定义',
        id:'ZXZ_TEAM EFFECTIVE NUMBER'
    },{
        title:'团队创建协议',
        id:'ZXZ_TEAM_PROFILE_AGREEMENT'
    },{
        title:'团队结算规则',
        id:'ZXZ_TEAM_PROFILE_SETTLEMENT_RULE'
    },{
        title:'团长社群',
        id:'ZXZ_TEAM_LEADER_GROUP'
    },{
        title:'纳税说明',
        id:'ZXZ_TAX_EXPLANATION'
    },{
        title:'团队创建说明',
        id:'ZXZ_TEAM_CREATE_EXPLANATION'
    },
 ]
};

getNotifyColumnList()
// 状态change事件
const changeStatus = (e:boolean,row:any,index:any) => {
  if(!loading.value){
      console.log(e)
      let par = {
        id:row.Id,
        status:(e?1:0) + '',
      }
      setModifyNotify(par)
  }
  setTimeout(() => {
    loading.value = false;
  }, 100);
}
const setModifyNotify = (par:object)=>{
  modifyNotify(par).then(res =>{
    if(res.code == 200){
      getTableData()
    }
  })
}
const tooltipType = ref('')
const historyPeopleLevelArr = ref([]);
const getHistoryPeopleLevel = (row:any)=>{
    if(row.property == ''){
        historyPeopleLevel({id:row.Id}).then(res => {
            if(res.code == 200){
                historyPeopleLevelArr.value =res.data.list 
            }else{
                ElMessage.success(res.message);
            }
        })
    }
    
}
//新建项目通知
const handleAdd = (item:any) => {
  router.push({
    path: '/backstagerpzzm/notificationMessage/addSysArticle',
    query:{
      id:item!.id,
      title:item!.title,
    }
  })
}//新建项目通知
const goApp = (item:any) => {
  debugger
  let host = window.location.host;
   let hostname = window.location.hostname;
  let url = ''
  debugger
  if(host.indexOf('localhost') > -1 || host.indexOf('192.168') > -1 ){
    url = 'http://192.168.13.119:8080/work/pages/article/article?id='+item.id+'&title='+item.title
  }else {
     if(host.indexOf('47.') > -1){
      url = 'http://47.93.156.6:8087/work/pages/article/article?id='+item.id +'&title='+item.title
    }else if(host.indexOf('new.zhaixiaozhi.com')> -1){
       url = 'http://' + hostname + ':8888/work/pages/article/article?id='+item.id +'&title='+item.title
    }else{
      url = 'https://' + hostname + '/work/pages/article/article?id='+item.id +'&title='+item.title
    } 
  }
  window.open(url)
}
// 操作
const handleOpt = (row: any ,index:Number,type: Number) => {
   let par = {
      id:row.Id,
    }
  if(type == 7){
    par.sort = row.sort
    setModifyNotify(par)
    return
  }
  ElMessageBox.confirm(`是否确认当前操作?`, "", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "success",
  })
    .then(() => {
      if(type == 6){//批量删除
        par = {
          ids: selectData.value,
        }
        if(checkAll.value){
          par.ids = []
        }
         delete par.id
      }else if(type == 4){
        par = {
          ids:[row.Id],
        }
        delete par.id
      }
      
      setProfileUdate(par,row,index)
    })
    .catch(() => { });
};

const setProfileUdate = (par:any,)=> {
    deleteNotify(par).then(res => {
        if(res.code == 200){
           ElMessage.success('操作成功！');
           if(checkAll.value){
            checkAll.value = false
           }
           getTableData()
        }else{
           ElMessage.success(res.message);
        }
    })
}

const uploadObjImg = reactive({
  accept: ".png, .jpg, .jpeg",
});

const uploadFileFun = (fileInfo: any,row:any,index:any) => {
  let file = fileInfo.file;
  const fileType = [".png", ".jpg", ".jpeg"];
  const type = file.name.substr(file.name.lastIndexOf(".")).toLowerCase();
  // 上传类型限制
  if (!fileType.includes(type)) {
    let type = fileType.join("，");
    ElMessage.error(`温馨提示：只支持${type}格式的文件`);
    return;
  }
  // 上传大小限制
  const sizeLimit = file.size / 1024 / 1024 <= 5;
  if (!sizeLimit) {
    ElMessage.error("文件最大不能超过5MB");
    return;
  }

  let formData = new FormData();
  formData.append("file", file);
  formData.append("product_id", row.product_id);

  let data = {
    data: formData,
  };
  productPicture(data).then((res: any) => {
    if (res.code) {
      ElMessage.success(`上传成功`);
      tableData.value.splice(index,1,{...row,product_picture_path:res.data})
    }
  });
};


// 导出题目答案与表格
const exportBatchLoading = ref(false);
const exportSingleLoading = ref(false);
const exportExcelFun = () => {
  exportBatchLoading.value = true;
  exportExcelPost(selectData.value, selectProjectIdsData.value)
}
// 导出通用函数
const exportExcelPost = (topic_ids: any, project_ids: any) => {
  let data = {
    topic_ids: topic_ids, // array[interger]
    // project_ids: project_ids, // array[string]
  }
  exportExcel(data).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success('导出成功');
      window.open(res.data);
    }
  }).finally(() => {
    exportBatchLoading.value = false;
    exportSingleLoading.value = false;
  })
}
// 批量导入用户
const uploadObj = reactive({
  fileType: ['.xls', '.xlsx'],
  accept: '.xls, .xlsx', // 文件上传类型
  multiple: false, // 是否支持多选
  visible: false,
  title: '',
  url: '', // 批量导入用户接口地址
  type:'team',
  downloadObj: {
    name: '',
    url: ''
  }
});
const closeUploadDialog = ()=>{
    uploadObj.visible = false
}
const refreshTable = ()=>{
    ElMessage.success("导入成功！")
    closeUploadDialog()
}

const handleBatchImport = () => {
  let obj1 = {
    title:'批量上架/下架商品',
    url:'商品设置表'
  } 
  uploadObj.visible = true;
  uploadObj.title =  obj1.title;
  uploadObj.url = '/admin/product/excel/imports';
  uploadObj.downloadObj.name = obj1.url; // excel模板名称
  uploadObj.downloadObj.url = `${ossPrefixNew}${obj1.url}.xlsx`; // excel模板下载地址
}
getTableData(true);

</script>

<style lang="scss" scoped>
.layout-container-form {
  position: relative;
  .el-form-item-flexstart{
      display: flex;
      justify-content: flex-start;
      flex-wrap: nowrap;
  }
}

.layout-container-form-search {
  width: 100%;
  display: inline-block !important;
  justify-content: flex-start !important;

  .search-btn {
    margin-right: 10px;
    ;
  }
}

.layout-container-opt {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 10px;
  margin-top: 10px;
}

.split-line {
  margin: 0 8px;
  color: #ccc;
}

.image-slot {
  width: 50px;
  height: 50px;
  background: #fafafa;
  color: #ccc;
  font-size: 12px;
  cursor: pointer;
}
.cup{
    cursor: pointer;
}
.blue{
    color: #027db4;
}
</style>
